//
//  ForgotPasswordViewController.m
//  TryShoppingHD
//
//  Created by Mr.Lee on 16/7/20.
//  Copyright © 2016年 Reabam. All rights reserved.
//

#import "ForgotPasswordViewController.h"
#import "SystemResetPwdViewController.h"
#import "HttpRequest.h"
#import "LoginViewController.h"
#import "SeverData.h"
#import "IQKeyboardManager.h"
@interface ForgotPasswordViewController ()<UITextFieldDelegate>
@end
@implementation ForgotPasswordViewController
{
    UITextField *userNameTextField;
    UITextField *passwordTextField;
    UITextField *verificationCode;
    UITextField *phoneTextField;
    UIButton *ToObtain;
    UIView* _view1;
}

- (void)setTitleName:(NSString *)titleName{
    _titleName = titleName;
}

- (void)setMemberId:(NSString *)memberId{
    _memberId = memberId;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // 设置导航条
    [self setUpNavigationBar];
    // 设置UI
    [self setUpUI];

}

#pragma mark -- 设置导航条
- (void)setUpNavigationBar {
    //隐藏系统导航条
    self.navigationController.navigationBarHidden = YES;
    // 自定义导航条
    
//    TabbarSafeBottomMargin
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, StatusBarHeight, ScreenWidth, 44)];
    navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navView];
    
    // 设置title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(0, 0, ScreenWidth, 44);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:17];
    if ([self.titleName isEqualToString:@"找回密码"]) {
        titleLabel.text = @"找回密码";
    } else if ([self.titleName isEqualToString:@"绑定手机"]){
        titleLabel.text = @"绑定手机";
    }
    [navView addSubview:titleLabel];
    
    // 返回按钮
    UIButton *backBtn = [[UIButton alloc] init];
    backBtn.frame = CGRectMake(8, 0, 44, 44);
    [backBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    
    
    // 分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 44-0.5, ScreenWidth, 0.5)];
    lineView.backgroundColor = qianhuiColor;
    [navView addSubview:lineView];
}

#pragma mark --  点击返回
-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- 设置UI
- (void)setUpUI{
    // 找回密码框
    UIView* view1 = [[UIView alloc]initWithFrame:CGRectMake(0,105+StatusBarHeight, ScreenWidth, 250)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(15, 88/2, view1.width-30, 0.5)];
    line1.backgroundColor = qianhuiColor;
    [view1 addSubview:line1];
    UIView *line3 = [[UIView alloc]initWithFrame:CGRectMake(15,106, view1.width-30, 0.5)];
    line3.backgroundColor = qianhuiColor;
    [view1 addSubview:line3];
    _view1 = view1;
    
    
    // 手机号码
    phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, view1.width-35, 44)];
    [phoneTextField setBorderStyle:UITextBorderStyleNone]; //外框类型
    phoneTextField.keyboardType = UIKeyboardTypeDecimalPad;
    phoneTextField.placeholder = @"请输入手机号码"; //默认显示的字
    phoneTextField.font = [UIFont systemFontOfSize: 17.0];
    phoneTextField.returnKeyType = UIReturnKeyDone;
    phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    phoneTextField.delegate = self;
    [phoneTextField addTarget:self action:@selector(userNumberLimitTextLength:) forControlEvents:UIControlEventEditingChanged];
    [view1 addSubview:phoneTextField];
    if ([self.titleName isEqualToString:@"找回密码"]) {
        NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
        NSString* UserName = [userDefault objectForKey:@"userNameTextField"];
        phoneTextField.text=UserName;
    } else if ([self.titleName isEqualToString:@"绑定手机"]){
        phoneTextField.text = @"";
    }
    
    
    // 手机验证码
    verificationCode = [[UITextField alloc] initWithFrame:CGRectMake(15, 58, 200, 44)];
    [verificationCode setBorderStyle:UITextBorderStyleNone]; //外框类型
    verificationCode.placeholder = @"输入手机验证码"; //默认显示的字
    verificationCode.secureTextEntry = NO; //密码
    verificationCode.font = [UIFont systemFontOfSize: 17.0];
    verificationCode.keyboardType = UIKeyboardTypeDecimalPad;
    verificationCode.autocorrectionType = UITextAutocorrectionTypeNo;
    verificationCode.autocapitalizationType = UITextAutocapitalizationTypeNone;
    verificationCode.returnKeyType = UIReturnKeyDone;
    verificationCode.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    verificationCode.delegate = self;
    [view1 addSubview:verificationCode];
    
    // 验证码按钮
    CGFloat maxX = CGRectGetMaxX(view1.bounds);
    ToObtain = [[UIButton alloc] initWithFrame:CGRectMake(maxX - 120, 63, 100, 25)];
    [ToObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
    ToObtain.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [ToObtain.layer setCornerRadius:3.0]; //设置矩圆角半径
    [ToObtain.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){224/255.0, 224/255.0, 224/255.0, 1.0});
    [ToObtain.layer setBorderColor:tureBTncolorref];//边框颜色
    [ToObtain setTitleColor:hongseColor forState:UIControlStateNormal];
    ToObtain .titleLabel.textAlignment=NSTextAlignmentRight;
    [ToObtain addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:ToObtain];
    
    
    // 绑定手机
    if ([self.titleName isEqualToString:@"绑定手机"]) {
        CGFloat y = _view1.frame.origin.y;
        CGFloat x = _view1.frame.origin.x;
        userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(x+15, y-44, _view1.width-30, 44)];
        [userNameTextField setBorderStyle:UITextBorderStyleNone]; //外框类型
        userNameTextField.keyboardType = UIKeyboardTypeDefault;
        userNameTextField.placeholder = @"请输入会员姓名"; //默认显示的字
        userNameTextField.font = [UIFont systemFontOfSize: 17.0];
        userNameTextField.returnKeyType = UIReturnKeyDone;
        userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        userNameTextField.delegate = self;
        [userNameTextField addTarget:self action:@selector(userNumberLimitTextLength:) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:userNameTextField];
        userNameTextField.text=_userName;
        UILabel *line2 = [[UILabel alloc]initWithFrame:CGRectMake(x+15,userNameTextField.bottom-0.45, _view1.width-30, 0.45)];
        line2.backgroundColor = qianhuiColor;
        [self.view addSubview:line2];
    }
    
    // 登录按钮
    UIButton* login = [[UIButton alloc] initWithFrame:CGRectMake(15,  303, ScreenWidth - 30, 44)];
    [login setTitle:@"下一步" forState:UIControlStateNormal];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    login.backgroundColor=ZhuTibtn;
    [login.layer setCornerRadius:4.0]; //设置矩圆角半径
    [login.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace1 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref1 = CGColorCreate(tureBTnSpace1,(CGFloat[]){204.0/255.0,204.0/255.0, 204.0/255.0, 1.0 });
    [login.layer setBorderColor:tureBTncolorref1];//边框颜色
    [login addTarget:self action:@selector(regist:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:login];
}

-(void)regist:(UIButton*)sender{
    
//    SystemResetPwdViewController *generateVC=[[SystemResetPwdViewController alloc] init];
//    generateVC.view.backgroundColor = [UIColor whiteColor];
//    generateVC.ucode=phoneTextField.text;
//    generateVC.vcode=@"";
//    [self.navigationController pushViewController:generateVC animated:YES];
//    return;
    
    
    if ([self.titleName isEqualToString:@"找回密码"]) {//导购或者店长找回密码
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:phoneTextField.text forKey:@"ucode"];
        
        [params setValue:verificationCode.text forKey:@"mcode"];
        NSLog(@"====%@",params);
        [HttpRequest requestData1:@"Common/ForgetPwd" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"====%@",severDataDict.dataDict);
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    SystemResetPwdViewController *generateVC=[[SystemResetPwdViewController alloc] init];
                    generateVC.view.backgroundColor = [UIColor whiteColor];
                    generateVC.ucode=phoneTextField.text;
                    generateVC.vcode=[severDataDict.dataDict objectForKey:@"vcode"];
                    [self.navigationController pushViewController:generateVC animated:YES];
                }else{
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
        }];
        
    }else  if ([self.titleName isEqualToString:@"绑定手机"]) {
        //绑定会员手机
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* tokenId = [user objectForKey:@"tokenId"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:tokenId forKey:@"tokenId"];
        [params setValue:self.memberId forKey:@"memberId"];
        [params setValue:phoneTextField.text forKey:@"phone"];
        [params setValue:userNameTextField.text forKey:@"userName"];
        [params setValue:verificationCode.text forKey:@"vCode"];
        NSLog(@"====%@",params);
        
        [HttpRequest requestData:@"Business/Member/BindPhone" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"====%@",severDataDict.dataDict);
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    
//                    [_delegate secondViewController:self updateMemberPhoneText:@"s"];
                    
                    // 更新会员绑定手机号码通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdataBindMemberPhoneNum" object:self];
                    
//                    [self.navigationController popViewControllerAnimated:YES];
                    [self.view removeFromSuperview];
                    [self removeFromParentViewController];
                    
                }else{
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
            }
            else
            {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
            }
        }];
        
    }  else  if ([self.titleName isEqualToString:@"换绑手机"]) {  //换绑手机
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* tokenId = [user objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:tokenId forKey:@"tokenId"];
            [params setValue:phoneTextField.text forKey:@"ucode"];
            [params setValue:verificationCode.text forKey:@"mcode"];
            NSLog(@"====%@",params);
    
            [HttpRequest requestData1:@"Common/ValidPhone" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    NSLog(@"====%@",severDataDict.dataDict);
    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                        [MBProgressHUD hideProgressHUDInternal:self.view];
//                        ValidPhoneViewController *generateVC=[[ValidPhoneViewController alloc] init];
//                        generateVC.vcode=[severDataDict.dataDict objectForKey:@"vcode"];
//                        [self.navigationController pushViewController:generateVC animated:YES];
    
    
                    }else{
                        [MBProgressHUD hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                    }
                } else {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
            }];
            
    
            
        }
    
    
}

//账号长度限制
- (void)userNumberLimitTextLength:(UITextField*)textField
{
    if ([textField.text length] > 11)
    {
        textField.text = [textField.text substringToIndex:11];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    
    return YES;
}

-(void)startTime{
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    
    if ([phoneTextField.text length] != 11)
    {
        [TSAlertTool showAlertMessage:@"手机输入有误"];
    }
    else
    {
        
        __block int timeout=60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    
                    [ToObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
                    ToObtain.userInteractionEnabled = YES;
                });
            }else{
                //            int minutes = timeout / 60;
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    //                NSLog(@"____%@",strTime);
                    if (strTime.intValue==59) {
                        NSLog(@"____%@",strTime);
             
                        
                        NSMutableDictionary *params = [NSMutableDictionary new];
                        [params setValue:phoneTextField.text forKey:@"mobile"];
                        
                        if ([self.titleName isEqualToString:@"绑定手机"]) {
                        
                            [params setValue:@"M" forKey:@"msgType"];
                            self.sat=@"System";
                            NSMutableDictionary *params = [NSMutableDictionary new];
                            [params setValue:phoneTextField.text forKey:@"mobile"];
                            [params setValue:@"M" forKey:@"msgType"];
                            [HttpRequest requestData:@"System/SendMsg" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                                if (isSuccess) {
                                    NSLog(@"====%@",severDataDict.dataDict);
                                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                        NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];
                                        [TSAlertTool showAlertMessage:ResultString];
                                        
                                    }else{
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                    }
                                    
                                } else {
                                    [MBProgressHUD hideProgressHUDInternal:self.view];
                                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                                }
                            }];

                        }else  if ([self.titleName isEqualToString:@"找回密码"]){
                        
                            [params setValue:@"F" forKey:@"msgType"];
                            [HttpRequest requestData1:@"Common/SendMsg" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                                if (isSuccess) {
                                    NSLog(@"====%@",severDataDict.dataDict);
                                    
                                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                        NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];
                                        [TSAlertTool showAlertMessage:ResultString];
                                    }else{
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                                    }
                                    
                                } else {
                                    [MBProgressHUD hideProgressHUDInternal:self.view];
                                    [MBProgressHUD showTextHudSub:@"连接失败" view:self.view];
                                    
                                }
                                
                            }];
                        }else if ([self.titleName isEqualToString:@"换绑手机"]){
                            [params setValue:@"R" forKey:@"msgType"];
                            self.sat=@"Common";
                            NSLog(@"====%@",params);
                            
                            [HttpRequest requestData1:[NSString stringWithFormat:@"%@/SendMsg", self.sat] params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                                if (isSuccess) {
                                    NSLog(@"====%@",severDataDict.dataDict);
                                    
                                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                        NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];
                                         [TSAlertTool showAlertMessage:ResultString];
                                    }else{
                                        [MBProgressHUD hideProgressHUDInternal:self.view];
                                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                                    }
                                    
                                } else {
                                    [MBProgressHUD hideProgressHUDInternal:self.view];
                                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                                }
                            }];
                        }
                    }
                    [ToObtain setTitle:[NSString stringWithFormat:@"%@秒重获",strTime] forState:UIControlStateNormal];
                    ToObtain.userInteractionEnabled = NO;
                    
                });
                timeout--;
                
            }
        });
        dispatch_resume(_timer);
        
    }
    
}

@end
